package com.srd.phone.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shengrongdai.srd.R;
import com.srd.phone.bean.UserInfo;
import com.srd.phone.utils.Constants;
import com.srd.phone.utils.FileUtils;
import com.srd.phone.utils.PreferenceUtils;
import com.srd.phone.utils.StorageUtils;
import com.srd.phone.utils.UpLoadSingleUtil;
import com.srd.phone.utils.UserUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 修改头像
 */
public class ChangeHeadActivity extends BaseActivity implements View.OnClickListener {

    private ImageView iv_head;

    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    private File tempFile = null;
    private Bitmap bitmap = null;

    private static final String PHOTO_FILE_NAME = "photo_head.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_head);

        initView();
        initData();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void initView() {
        tv_common_title.setText("修改头像");
        iv_head = (ImageView)findViewById(R.id.iv_head);
        findViewById(R.id.rl_camera).setOnClickListener(this);
        findViewById(R.id.rl_photo).setOnClickListener(this);
        findViewById(R.id.btn_submit).setOnClickListener(this);
    }

    public void initData() {
        UserInfo userInfo = UserUtils.getUserInfo();
        ImageLoader.getInstance().displayImage(Constants.BASE_HEAD_URL + userInfo.uid + "/" + userInfo.src, iv_head);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_camera:  // 相机
                openCamera();
                break;
            case R.id.rl_photo:   // 相册
                openGallery();
                break;
            case R.id.btn_submit:  // 提交
                uploadPhotoFile();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if(bitmap != null){
            bitmap.recycle();
            bitmap = null;
        }
        super.onDestroy();
    }

    /** 上传图片  */
    public void uploadPhotoFile() {
        try {

            saveBitmapToFile(bitmap);
            showWaitingDialog();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    UpLoadSingleUtil upLoadSingleUtil = UpLoadSingleUtil.getInstance();
                    upLoadSingleUtil.setUploadProcessListener(new UpLoadSingleUtil.OnUploadProcessListener() {
                        @Override
                        public void onUploadDone(int responseCode, String message) {
                            Log.d("responseCode", message);
                            cancelWaitingDialog();
                            Looper.prepare();
                            if(responseCode == 200){
                                try {
                                    JSONObject jsonObj = new JSONObject(message);
                                    String data = jsonObj.getString("data");
                                    String str = data.substring(0, data.lastIndexOf("/") );
                                    PreferenceUtils.getInstance().putData("user.src", data.substring(data.lastIndexOf("/") + 1, data.length()));
                                    PreferenceUtils.getInstance().putData("user.uid", str.substring(str.lastIndexOf("/") + 1, str.length()));
                                    toastShow("头像上传成功~");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }else{
                                toastShow("头像上传失败,请重试~");
                            }
                            Looper.loop();
                        }

                        @Override
                        public void onUploadProcess(int uploadSize) {}

                        @Override
                        public void initUpload(long fileSize) {}
                    });

                    upLoadSingleUtil.uploadFile(StorageUtils.getCacheFile(ChangeHeadActivity.this) + PHOTO_FILE_NAME, "jpg", Constants.UPLOAD_HEAD_IMG, null);
                }
            }).start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 从相册获取 */
    public void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }

    /** 从相机获取 */
    public void openCamera() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        if (FileUtils.checkSdCard())
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(StorageUtils.getCacheFile(this), PHOTO_FILE_NAME)));
        else
        {
            toastShow("未找到存储卡，无法存储照片~");
            return;
        }
        startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                Uri uri = data.getData();
                crop(uri);
            }
        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            if (FileUtils.checkSdCard()) {
                tempFile = new File(StorageUtils.getCacheFile(this), PHOTO_FILE_NAME);
                crop(Uri.fromFile(tempFile));
            } else {
                Toast.makeText(this, "未找到存储卡，无法存储照片~", Toast.LENGTH_LONG).show();
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            try {
                if(bitmap != null)
                    bitmap.recycle();
                bitmap = data.getParcelableExtra("data");
                iv_head.setImageBitmap(bitmap);

                boolean delete = tempFile.delete();
                Log.d("delete = ", delete + "");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);   // 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }


    public void saveBitmapToFile(Bitmap mBitmap)  {
        File file = new File(StorageUtils.getCacheFile(this) + PHOTO_FILE_NAME);
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}